package com.yswee.mallnavi.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.yswee.framework.data.parser.IParser;
import com.yswee.framework.net.http.Callback;
import com.yswee.framework.net.http.Entity;
import com.yswee.framework.utils.OSUtils;
import com.yswee.mallnavi.model.common.CommonModel;
import com.yswee.mallnavi.receiver.NotifyReceiver;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class CoreService extends Service {

	private static final String TAG = CoreService.class.getSimpleName();
	private static final int MAX_HEART_ERROR = 10;
	//心跳
	private static final int HEART_INTERVAL_SECONDS = 61;

	private CommonModel mCommonModel;
	private int mHeartError;

	private ScheduledExecutorService mScheduler;


	@Override
	public void onCreate() {
		super.onCreate();
		Intent intent = new Intent(this, NotifyReceiver.class);
		startForeground(1024, OSUtils.getForegroundNotification(intent));
		OSUtils.showPopupWindow();
		// 初始化定时器并启动心跳任务
		mScheduler = Executors.newSingleThreadScheduledExecutor();
		mScheduler.scheduleWithFixedDelay(this::sendHeart, 0, HEART_INTERVAL_SECONDS, TimeUnit.SECONDS);

		Log.i(TAG, "CoreService started and heart scheduler initiated.");


    }
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}




	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	


	@Override
	public void onDestroy() {
		if (mScheduler != null) {
			mScheduler.shutdown();
			try {
				if (!mScheduler.awaitTermination(5, TimeUnit.SECONDS)) {
					mScheduler.shutdownNow();
				}
			} catch (InterruptedException e) {
				mScheduler.shutdownNow();
				Thread.currentThread().interrupt();
			}
		}
		stopForeground(true);
		super.onDestroy();
	}
	@Override
	public void onTaskRemoved(Intent rootIntent) {
		super.onTaskRemoved(rootIntent);
		stopSelf(); // 确保服务关闭
	}



	private void sendHeart() {

		try {

			if (mCommonModel == null) {
				mCommonModel = new CommonModel(null);
			}
			mCommonModel.sendHeart(new Callback<Void>() {
				@Override
				public void onFinish(Entity<Void> entity) {
					IParser<Void> parser = entity.getParser();
					if (parser.getIsOk()) {
						mHeartError = 0;
					} else {
						mHeartError++;
					}
					checkHeartErrorLimit();
				}

				@Override
				public void onError(Entity<Void> entity) {
					mHeartError++;
					checkHeartErrorLimit();
				}
			});
		}
		catch (Exception e) {
			Log.e(TAG, "Heartbeat failed: ", e);
			mHeartError++;
			checkHeartErrorLimit();
		}

	}

	private void checkHeartErrorLimit() {
		if (mHeartError >= MAX_HEART_ERROR) {
			Log.e(TAG, "Max heartbeat error limit reached. Consider restart or alert.");

		}
	}

	
}